---@装饰器 统一校验用户登录有效性
local _auth = class("AuthDecorator")
--======================================
--default params
local d = Ding
local Logger = d.Logger
local Orm = d.Orm
--======================================
local ENUM_AUTHENTIC_ERROR = {
    ["MISS_REQUIRE_AUTHHEADER"] = 9001,
    ["GID_NOT_EXIST"] = 9002,
    ["TOKEN_NOT_EXPIREIN"] = 9003,
    ["SIGNATURE_COMP_MISSTAKE"] = 9004,
}

local AUTHENTIC_ERROR_TIP = {
    [9001] = "miss_require_authheader",
    [9002] = "gid_not_exist",
    [9003] = "token_not_expirein",
    [9004] = "signature_comp_misstake",
}

local REQUIRE_HEADERS = {
    "X-D-GID",
    "X-D-TOKEN",
    "X-D-SIGNATURE"
}

local EXPORTED_METHODS = {
    "base_auth_"
}

function _auth:init_()
end

function _auth:bind(target, ormusr, ormacusr)
    self:init_()
    d.setmethods(target, self, EXPORTED_METHODS)
    self._s = target

end

function _auth:unbind(target)
    d.unbind(target, EXPORTED_METHODS)
end

function _auth:_chk_require_header(reqobj)
    local headers = reqobj.get_headers()
    local gid = headers[REQUIRE_HEADERS[1]]
    -- --debug 
    if gid and tonumber(gid) <= 10 then 
        return true
    end
    for _, v in ipairs(REQUIRE_HEADERS) do 
        if not headers[v] then
            return false, ENUM_AUTHENTIC_ERROR["MISS_REQUIRE_AUTHHEADER"]
        end 
    end
    --chk gid 
    if not  self:_chk_gid(gid) then 
        return false, ENUM_AUTHENTIC_ERROR["GID_NOT_EXIST"]
    end
    --chk token 
    if not self:_chk_token(gid) then 
        return false, ENUM_AUTHENTIC_ERROR["TOKEN_NOT_EXPIREIN"]
    end
    --chk signature
    if not self:_chk_signature() then 
        return false, SIGNATURE_COMP_MISSTAKE
    end
    return true, gid
end

-- 检查连接的有效性
function _auth:base_auth_(reqobj)
    local ok, cont = self:_chk_require_header(reqobj)
    if not ok then 
        self._s:doerror(cont, AUTHENTIC_ERROR_TIP[cont])
        return false
    end
    return true, cont
end

function _auth:_chk_gid(gid)
    local orm_usr = Orm:get("usr")
    if not orm_usr then return false end 
    return orm_usr:find({gid = gid})
end

function _auth:_chk_token(gid)
    local orm_actusr = Orm:get("actusr")
    if not orm_actusr then return false end
    return orm_actusr:find({gid = gid})
end 

function _auth:_chk_signature()
    --todo
    return true 
end

return _auth
